#pragma once
#include<iostream>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<cstring>
#include<string>
#include"Log.hpp"

enum
{
    SOCKETERR = 2,
    BINDERR,
    LISTENERR,
};
const int backlog = 5;

class Sock
{
public:
    Sock()
    {

    }
    ~Sock()
    {

    }
public:
    void Socket()
    {

        sockfd_ = socket(AF_INET, SOCK_STREAM, 0);
        if(sockfd_ < 0)
        {
            lg(Fatal, "socket error, errno: %d, strerror: %s", errno, strerror(errno));
            exit(SOCKETERR);
        }
        int opt = 1;
        setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
    }
    void Bind(const uint16_t& port)
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        if(bind(sockfd_, (struct sockaddr*)&local, sizeof(local)) < 0)
        {
            lg(Fatal, "bind error, errno: %d, strerror: %s", errno, strerror(errno));
            exit(BINDERR);
        }
    }
    void Listen()
    {
        if(listen(sockfd_,backlog) < 0)
        {
            lg(Fatal, "listen error, errno: %d, strerror: %s", errno, strerror(errno));
            exit(LISTENERR);
        }
    }
    int Accept(std::string* clientip, uint16_t* clientport)
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        char buffer[4096];
        int newfd = accept(sockfd_, (struct sockaddr*)&client, &len);
        if(newfd < 0)
        {
            lg(Warning, "accept error, errno: %d, strerror: %s", errno, strerror(errno));
            return -1;
        }
        char ipstr[64];
        *clientport = ntohs(client.sin_port);
        inet_ntop(AF_INET, &client.sin_addr, ipstr, sizeof(ipstr));
        *clientip = ipstr;
        return newfd;
    }
    bool Connect(std::string &ip, uint16_t &port)
    {
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_port = htons(port);
        //peer.sin_addr.s_addr = inet_addr(ip.c_str());
        inet_pton(AF_INET, ip.c_str(), &(peer.sin_addr));
        int n = connect(sockfd_,(struct sockaddr*)&peer, sizeof(peer));
        if(n == -1)
        {
            std::cerr << "connect to " << ip << ":" << port << " error" << std::endl;
            return false;
        }
        return true;
    }
    void Close()
    {
        close(sockfd_);
    }
    int Fd()
    {
        return sockfd_;
    }
private:
    int sockfd_;
};